import { getAllCollectData } from '@/api/CollectRequest.js'
import SocketMoudle from '@/views/js/SocketMoudle.js'
import { robot_pose, agv_pose, fixture1_pose, fixture2_pose } from '@/views/data/PoseData.js'
import { ArmData } from '@/views/data/DeviceData.js'
import AreaLableData from '@/views/data/AreaLableData.js'
import XJPostionData from '@/views/data/XJPostionData.js'
import { abs } from '../../../packages/src/nodes/math/MathNode'
import { xingjiaTypeTempData } from '../data/DeviceData'
// #region  数据对接
const ArmDataMap = new Map()
const AGVDataMap = new Map()
const XJDataMap = new Map()
const XJDataMap2 = new Map()
const XJDataMapTemp = new Map()// 动态型架
const GYTXDataMap = new Map()
const PogoDataMap = new Map()
const agvPosRoom = 1000 // 厂家单位毫米
const DevicwRoom = 1000 // 厂家单位毫米
let socket = null

function InitSocket (socketCallBack) {
  window.sandbox.logger.log('初始化socket')
  socket = new SocketMoudle(window.SocketUrl)
  socket.addEventListener('end', data => {
    const obj = JSON.parse(data)
    socketCallBack?.(obj)
    if (!obj.key) {
      handleOtherData(obj)
      StartAgvGroup(obj, true)
    }
  })
}

function handleOtherData (arrayData) {
  arrayData.forEach(item => {
    const type = getDeviceType(item.modelId)
    switch (type) {
      // case 'AGV':
      //   RefreshAGVData(item, true)
      //   break
      case 'robot':
        RefreshRobotData(item, true)
        break
      case 'fixture1':
        Refreshfixture1Data(item.modelId, item.collectValue, true)
        break
      case 'fixture2':
        Refreshfixture2Data(item.modelId, item.collectValue, true)
        break
      case 'area13-east13':
      case 'area13-west13':
        RefreshEastArea13Data(item, true)
        break
      case 'plate':
        RefreshPlateData(item, true)
        break
      case 'door':
        RefreshDoorData(item, true)
        break
      case 'Pogo':
        RefreshPogoData(item, true)
        break
      case 'bridge':
        RefreshbridgeData(item, true)
        break
      case 'fixtureInfo':
        // RefreshfixtureInfoData(item, true)
        break
    }
  })
}
// 初始化型架位置
function RefreshfixtureInfoData (item, isTween) {
  if (item.collectValue === '{}') {
    window.sandbox.logger.log(item.modelId, 'fixtureInfo数据为空', item.collectValue)
    return
  }
  const prefix = item.modelId.replace('fixtureInfo', '')
  let key = ''
  if (parseInt(prefix) <= 5) {
    key = `fixture1-P0${prefix}`
  } else if (parseInt(prefix) === 10) {
    key = `fixture2-P${prefix}`
  } else {
    key = `fixture2-P0${prefix}`
  }

  const targetMap = key.includes('fixture1') ? XJDataMap : XJDataMap2
  const model = targetMap.get(key)
  if (model) {
    const jsonData = JSON.parse(item.collectValue)
    const xjItem = XJPostionData.find(xj => jsonData.型架当前位置.includes(xj.stationName))
    console.log(jsonData.型架当前位置, item.modelId)
    if (xjItem) {
      // model.position = xjItem.position
      const offect = key.includes('fixture1') ? 0 : xjItem.offect

      const value01 = { m0FixtureMOveX: xjItem.position.x * 1000 + offect * 1000, m0FixtureMOveZ: xjItem.position.z * 1000, m0FixtureMOveY: xjItem.position.y * 1000 }
      const item = { modelId: key, collectValue: JSON.stringify(value01) }
      if (key.includes('fixture1')) {
        Refreshfixture1Data(item.modelId, item.collectValue, isTween)
      } else if (key.includes('fixture2')) {
        Refreshfixture2Data(item.modelId, item.collectValue, isTween)
      }
    } else {
      console.warn('未找到 key:', key)
    }
  } else {
    console.warn('未找到 key:', key)
  }
}

function getDeviceType (deviceName) {
  if (deviceName.includes('robot')) {
    return 'robot'
  } else if (deviceName.includes('AGV')) {
    return 'AGV'
  } else if (deviceName.includes('fixture1')) {
    return 'fixture1'
  } else if (deviceName.includes('fixture2')) {
    return 'fixture2'
  } else if (deviceName.includes('area13-east13')) {
    return 'area13-east13'
  } else if (deviceName.includes('area13-west13')) {
    return 'area13-west13'
  } else if (deviceName.includes('plate')) {
    return 'plate'
  } else if (deviceName.includes('door')) {
    return 'door'
  } else if (deviceName.includes('bridge')) {
    return 'bridge'
  } else if (deviceName.includes('fixtureInfo')) {
    return 'fixtureInfo'
  } else {
    return 'unknown' // 如果都不匹配，返回未知类型
  }
}

function RefreshbridgeData (item, isTween) {
  if (item.collectValue === '{}') {
    window.sandbox.logger.log(item.modelId, 'bridge数据为空', item.collectValue)
    return
  }
  const pose = {}
  let fixtureMappings = null
  const fixtureMappings1 = [
    { key: 'locationValue', prop: '一节臂 MoveX' }
  ]
  const fixtureMappings2 = [
    { key: 'locationValue', prop: '二节臂 MoveX' }
  ]

  switch (item.modelId) {
    case 'GYX-area11_A_bridge11':
      fixtureMappings = fixtureMappings1
      break
    case 'GYX-area11_B_bridge11':
      fixtureMappings = fixtureMappings2
      break
  }

  const jsonData = JSON.parse(item.collectValue)
  if (GYTXDataMap.has('GYX-brige')) {
    const handleM = GYTXDataMap.get('GYX-brige')
    fixtureMappings.forEach(({ key, prop }) => {
      if (jsonData.hasOwnProperty(key)) {
        pose[prop] = jsonData[key] / DevicwRoom
      }
    })
    window.sandbox.logger.log('刷新bridge', item.modelId, item.collectValue, pose)
    updatedhandleData(pose, handleM, isTween)
  }
}

function RefreshDoorData (item, isTween) {
  const modelId = item.modelId
  const collectValue = item.collectValue
  if (collectValue === '{}') {
    window.sandbox.logger.log(modelId, 'EastOrWest13数据为空', collectValue)
    return
  }
  const jsonData = JSON.parse(collectValue)
  window.sandbox.logger.log('刷新Door', modelId, jsonData)
  const handleM = GYTXDataMap.get('GYX-area13-Door')
  const robot_pose = {}
  switch (modelId) {
    case 'GYX-area13-left13_door13':
      robot_pose['upmen01 yRoll'] = jsonData.bit0 ? -90 : 0
      robot_pose['upmen02 yRoll'] = jsonData.bit0 ? 90 : 0
      robot_pose['upmen03 yRoll'] = jsonData.bit1 ? -90 : 0
      robot_pose['upmen04 yRoll'] = jsonData.bit1 ? 90 : 0
      robot_pose['upmen05 yRoll'] = jsonData.bit2 ? -90 : 0
      robot_pose['upmen06 yRoll'] = jsonData.bit2 ? 90 : 0
      robot_pose['upmen07 yRoll'] = jsonData.bit3 ? -90 : 0
      robot_pose['upmen08 yRoll'] = jsonData.bit3 ? 90 : 0
      break
    case 'GYX-area13-right13_door13':
      robot_pose['downmen01 yRoll'] = jsonData.bit0 ? 90 : 0
      robot_pose['downmen02 yRoll'] = jsonData.bit0 ? -90 : 0
      robot_pose['downmen03 yRoll'] = jsonData.bit1 ? 90 : 0
      robot_pose['downmen04 yRoll'] = jsonData.bit1 ? -90 : 0
      robot_pose['downmen05 yRoll'] = jsonData.bit2 ? 90 : 0
      robot_pose['downmen06 yRoll'] = jsonData.bit2 ? -90 : 0
      robot_pose['downmen07 yRoll'] = jsonData.bit3 ? 90 : 0
      robot_pose['downmen08 yRoll'] = jsonData.bit3 ? -90 : 0
      break
  }
  window.sandbox.logger.log('刷新新EastOrWest13', modelId, robot_pose)
  updatedhandleData(robot_pose, handleM, isTween)
}

function RefreshPlateData (item, isTween) {
  const modelId = item.modelId
  const collectValue = item.collectValue
  if (collectValue === '{}') {
    window.sandbox.logger.log(modelId, 'EastOrWest13数据为空', collectValue)
    return
  }
  const jsonData = JSON.parse(collectValue)
  // window.sandbox.logger.log("刷新EastOrWest13", modelId, jsonData);
  const handleM = GYTXDataMap.get('GYX-area13-plate')
  const robot_pose = {}
  switch (modelId) {
    case 'GYX-area13-left1_plate13':
      robot_pose['upban01 MoveX'] = jsonData.platePlace
      break
    case 'GYX-area13-left2_plate13':
      robot_pose['upban02 MoveX'] = jsonData.platePlace
      break
    case 'GYX-area13-left3_plate13':
      robot_pose['upban03 MoveX'] = jsonData.platePlace
      break
    case 'GYX-area13-left4_plate13':
      robot_pose['upban04 MoveX'] = jsonData.platePlace
      break
    case 'GYX-area13-left5_plate13':
      robot_pose['upban05 MoveX'] = jsonData.platePlace
      break
    case 'GYX-area13-left6_plate13':
      robot_pose['upban06 MoveX'] = jsonData.platePlace
      break
    case 'GYX-area13-left7_plate13':
      robot_pose['upban07 MoveX'] = jsonData.platePlace
      break
    case 'GYX-area13-left8_plate13':
      robot_pose['upban08 MoveX'] = jsonData.platePlace
      break
    case 'GYX-area13-left9_plate13':
      robot_pose['upban09 MoveX'] = jsonData.platePlace
      break
    case 'GYX-area13-left10_plate13':
      robot_pose['upban10 MoveX'] = jsonData.platePlace
      break
    case 'GYX-area13-left11_plate13':
      robot_pose['upban11 MoveX'] = jsonData.platePlace
      break
    case 'GYX-area13-left12_plate13':
      robot_pose['upban12 MoveX'] = jsonData.platePlace
      break
    case 'GYX-area13-right1_plate13':
      robot_pose['downban01 MoveX'] = -jsonData.platePlace
      break
    case 'GYX-area13-right2_plate13':
      robot_pose['downban02 MoveX'] = -jsonData.platePlace
      break
    case 'GYX-area13-right3_plate13':
      robot_pose['downban03 MoveX'] = -jsonData.platePlace
      break
    case 'GYX-area13-right4_plate13':
      robot_pose['downban04 MoveX'] = -jsonData.platePlace
      break
    case 'GYX-area13-right5_plate13':
      robot_pose['downban05 MoveX'] = jsonData.platePlace
      break
    case 'GYX-area13-right6_plate13':
      robot_pose['downban06 MoveX'] = -jsonData.platePlace
      break
    case 'GYX-area13-right7_plate13':
      robot_pose['downban07 MoveX'] = jsonData.platePlace
      break
    case 'GYX-area13-right8_plate13':
      robot_pose['downban08 MoveX'] = -jsonData.platePlace
      break
    case 'GYX-area13-right9_plate13':
      robot_pose['downban09 MoveX'] = -jsonData.platePlace
      break
    case 'GYX-area13-right10_plate13':
      robot_pose['downban10 MoveX'] = -jsonData.platePlace
      break
    case 'GYX-area13-right11_plate13':
      robot_pose['downban11 MoveX'] = -jsonData.platePlace
      break
    case 'GYX-area13-right12_plate13':
      robot_pose['downban12 MoveX'] = -jsonData.platePlace
      break
  }
  window.sandbox.logger.log('刷新新PlateData', modelId, robot_pose)
  updatedhandleData(robot_pose, handleM, isTween)
}

function RefreshEastArea13Data (item, isTween) {
  const modelId = item.modelId
  const collectValue = item.collectValue
  if (collectValue === '{}') {
    window.sandbox.logger.log(modelId, 'EastOrWest13数据为空', collectValue)
    return
  }
  const jsonData = JSON.parse(collectValue)
  // window.sandbox.logger.log("刷新EastOrWest13", modelId, jsonData);
  const handleM = GYTXDataMap.get('GYX-area13-east13')
  const robot_pose = {}
  if (!jsonData.hasOwnProperty('platePlace')) {
    window.sandbox.logger.log(modelId, '没有属性platePlace')
    return
  }
  switch (modelId) {
    case 'GYX-area13-west13':
      // robot_pose['一节臂 MoveX'] = -jsonData.platePlace
      robot_pose['一节臂 MoveX'] = -GetGYXarea13east13(parseInt(jsonData.platePlace))
      break
    case 'GYX-area13-east13':
      // robot_pose['二节臂 MoveX'] = jsonData.platePlace
      robot_pose['二节臂 MoveX'] = GetGYXarea13east13(parseInt(jsonData.platePlace))
      break
  }
  window.sandbox.logger.log('刷新新EastOrWest13', modelId, robot_pose)
  updatedhandleData(robot_pose, handleM, isTween)
}

function GetGYXarea13east13 (level) {
  const T1_2 = 1.22
  const T2_3 = 0.66
  const T3_4 = 1.08
  const T4_5 = 1.25
  const T5_6 = 1.38
  let distance = 0
  switch (level) {
    case 1:
      distance = 0
      break
    case 2:
      distance = distance + T1_2
      break
    case 3:
      distance = distance + T1_2 + T2_3
      break
    case 4:
      distance = distance + T1_2 + T2_3 + T3_4
      break
    case 5:
      distance = distance + T1_2 + T2_3 + T3_4 + T4_5
      break
    case 6:
      distance = distance + T1_2 + T2_3 + T3_4 + T4_5 + T5_6
      break
  }
  return distance
}
function GetGYXarea13west13 (level) {
  const T1_2 = 0.98
  const T2_3 = 0.94
  const T3_4 = 0.87
  const T4_5 = 0.84
  const T5_6 = 0.8
  let distance = 0
  switch (level) {
    case 1:
      distance = 0
      break
    case 2:
      distance = distance + T1_2
      break
    case 3:
      distance = distance + T1_2 + T2_3
      break
    case 4:
      distance = distance + T1_2 + T2_3 + T3_4
      break
    case 5:
      distance = distance + T1_2 + T2_3 + T3_4 + T4_5
      break
    case 6:
      distance = distance + T1_2 + T2_3 + T3_4 + T4_5 + T5_6
      break
  }
  return distance
}

function RefreshPogoData (item, isTween) {
  const modelId = item.modelId
  const collectValue = item.collectValue
  if (collectValue === '{}') {
    window.sandbox.logger.log(modelId, '定位器数据为空', collectValue)
    return
  }
  const jsonData = JSON.parse(collectValue)
  const handleM = GYTXDataMap.get('GYXRight04')
  const robot_pose = {}
  const safeAssign = (key, value) => {
    if (value !== undefined && value !== null) {
      robot_pose[key] = value / DevicwRoom
    }
  }
  switch (modelId) {
    case 'GYX-area13_Pogo01':
      safeAssign('01Group MoveX', jsonData.xValue)
      safeAssign('01 MoveY', jsonData.yValue)
      safeAssign('01Group-01 MoveZ', jsonData.zValue)
      break
    case 'GYX-area13_Pogo02':
      safeAssign('02Group MoveX', jsonData.xValue)
      safeAssign('02 MoveY', jsonData.yValue)
      safeAssign('02Group-01 MoveZ', jsonData.zValue)
      break
    case 'GYX-area13_Pogo03':
      safeAssign('03Group MoveX', jsonData.xValue)
      safeAssign('03 MoveY', jsonData.yValue)
      safeAssign('03Group-01 MoveZ', jsonData.zValue)
      break
    case 'GYX-area13_Pogo04':
      safeAssign('04Group MoveX', jsonData.xValue)
      safeAssign('04 MoveY', jsonData.yValue)
      safeAssign('04Group-01 MoveZ', jsonData.zValue)
      break
    case 'GYX-area13_Pogo05':
      safeAssign('05Group MoveX', jsonData.xValue)
      safeAssign('05 MoveY', jsonData.yValue)
      safeAssign('05Group-01 MoveZ', jsonData.zValue)
      break
    case 'GYX-area13_Pogo06':
      safeAssign('06Group MoveX', jsonData.xValue)
      safeAssign('06 MoveY', jsonData.yValue)
      safeAssign('06Group-01 MoveZ', jsonData.zValue)
      break
    case 'GYX-area13_Pogo07':
      safeAssign('07Group MoveX', jsonData.xValue)
      safeAssign('07 MoveY', jsonData.yValue)
      safeAssign('07Group-01 MoveZ', jsonData.zValue)
      break
    case 'GYX-area13_Pogo08':
      safeAssign('08Group MoveX', jsonData.xValue)
      safeAssign('08 MoveY', jsonData.yValue)
      safeAssign('08Group-01 MoveZ', jsonData.zValue)
      break
  }
  window.sandbox.logger.log('刷新定位器数据', modelId, robot_pose)
  updatedhandleData(robot_pose, handleM, isTween)
}

function RefreshRobotData (item, isTween) {
  const robot_pose = {}
  const modelId = item.modelId
  const collectValue = item.collectValue
  if (collectValue === '{}') {
    window.sandbox.logger.log(modelId, '机械臂数据为空', collectValue)
    return
  }
  const jsonData = JSON.parse(collectValue)
  // window.sandbox.logger.log("刷新机械臂", modelId, jsonData);
  if (ArmDataMap.has(modelId)) {
    const handleM = ArmDataMap.get(modelId)
    robot_pose['一节臂 yRoll'] = jsonData.a1Value // -185 185
    robot_pose['二节臂 xRoll'] = jsonData.a2Value // -140 -5
    robot_pose['三节臂 xRoll'] = jsonData.a3Value // -120 168
    robot_pose['四节臂 zRoll'] = jsonData.a4Value // -350 350
    robot_pose['五节臂 zRoll'] = jsonData.a5Value // -122.5 122.5
    robot_pose['六节臂 zRoll'] = jsonData.a6Value // -350 350
    const itemConfig = ArmData.find(item => item.id === modelId)
    if (jsonData.hasOwnProperty('e1Value')) {
      if (itemConfig.isZ) {
        robot_pose['整体 MoveX'] = (itemConfig.isZ * jsonData.e1Value) / DevicwRoom // 0 10
      } else {
        robot_pose['整体 MoveX'] = jsonData.e1Value / DevicwRoom // 0 10
      }
    } else {
      robot_pose['整体 MoveX'] = 0 // 0 10
    }
    window.sandbox.logger.log('刷新机械臂', modelId, robot_pose)
    updatedhandleData(robot_pose, handleM, isTween)
  }
}

function RefreshAGVData (item, isTween) {
  const pose = {}
  const modelId = item.modelId
  const collectValue = item.collectValue
  if (collectValue === '{}') {
    window.sandbox.logger.log(modelId, 'AGV数据为空', collectValue)
    return
  }
  const jsonData = JSON.parse(collectValue)
  if (AGVDataMap.has(item.modelId)) {
    const handleM = AGVDataMap.get(item.modelId)
    // if(item.agvName!=='2号车')return
    if (!(jsonData.hasOwnProperty('xValue') || jsonData.hasOwnProperty('zValue'))) {
      window.sandbox.logger.log('没有坐标', item)
      return
    }
    pose['整体 MoveX'] = -jsonData.xValue / agvPosRoom
    pose['整体 MoveZ'] = jsonData.zValue / agvPosRoom
    pose['整体 yRoll'] = jsonData.toward
    const value = jsonData.lift / agvPosRoom
    pose['伸缩杆 yScale'] = value * 4
    pose['托盘 MoveY'] = value
    window.sandbox.logger.log('刷新AGV' + item.modelId, item, pose)
    updatedhandleData(pose, handleM, isTween)
  }
}
// 刷新
function Refreshfixture1Data (modelId, collectValue, isTween) {
  if (collectValue === '{}') {
    window.sandbox.logger.log(modelId, 'fixture1数据为空', collectValue)
    return
  }
  const jsonData = JSON.parse(collectValue)
  const pose = {}
  const fixtureMappings = [
    { key: 'm0Fixture', prop: '一节臂 MoveX' },
    { key: 'm0FixtureMOveX', prop: '整体 MoveX' },
    { key: 'm0FixtureMOveZ', prop: '整体 MoveZ' },
    { key: 'm0FixtureMOveY', prop: '整体 MoveY' }
  ]

  if (XJDataMap.has(modelId)) {
    const handleM = XJDataMap.get(modelId)
    fixtureMappings.forEach(({ key, prop }) => {
      if (jsonData.hasOwnProperty(key)) {
        pose[prop] = jsonData[key] / DevicwRoom
      }
    })
    window.sandbox.logger.log('刷新fixture1', modelId, collectValue, pose)

    updatedhandleData(pose, handleM, isTween)
  }
}

function Refreshfixture2Data (modelId, collectValue, isTween) {
  if (collectValue === '{}') {
    window.sandbox.logger.log(modelId, 'fixture2数据为空', collectValue)
    return
  }
  const pose = {}
  const fixtureMappings = [
    { key: 'm0Fixture', prop: '一节臂 MoveX' },
    { key: 'm1Fixture', prop: '二节臂 MoveX' },
    { key: 'm2Fixture', prop: '三节臂 MoveX' },
    { key: 'm3Fixture', prop: '四节臂 MoveX' },
    { key: 'm0FixtureMOveX', prop: '整体 MoveX' },
    { key: 'm0FixtureMOveZ', prop: '整体 MoveZ' },
    { key: 'm0FixtureMOveY', prop: '整体 MoveY' }
  ]

  const jsonData = JSON.parse(collectValue)
  if (XJDataMap2.has(modelId)) {
    const handleM = XJDataMap2.get(modelId)
    fixtureMappings.forEach(({ key, prop }) => {
      if (jsonData.hasOwnProperty(key)) {
        pose[prop] = jsonData[key] / DevicwRoom
      }
    })

    window.sandbox.logger.log('刷新fixture2', modelId, collectValue, pose)
    updatedhandleData(pose, handleM, isTween)
  }
}

// 刷新场景临时fixture数据
function RefreshfixtureTempData (modelId, collectValue, isTween) {
  if (collectValue === '{}') {
    window.sandbox.logger.log(modelId, 'fixture2数据为空', collectValue)
    return
  }
  const pose = {}
  const fixtureMappings = [
    { key: 'm0Fixture', prop: '一节臂 MoveX' },
    { key: 'm1Fixture', prop: '二节臂 MoveX' },
    { key: 'm2Fixture', prop: '三节臂 MoveX' },
    { key: 'm3Fixture', prop: '四节臂 MoveX' },
    { key: 'm0FixtureMOveX', prop: '整体 MoveX' },
    { key: 'm0FixtureMOveZ', prop: '整体 MoveZ' },
    { key: 'm0FixtureMOveY', prop: '整体 MoveY' }
  ]

  const jsonData = JSON.parse(collectValue)
  if (XJDataMapTemp.has(modelId)) {
    const handleM = XJDataMapTemp.get(modelId)
    fixtureMappings.forEach(({ key, prop }) => {
      if (jsonData.hasOwnProperty(key)) {
        pose[prop] = jsonData[key] / DevicwRoom
      }
    })

    window.sandbox.logger.log('刷新fixtureTemp', modelId, collectValue, pose)
    updatedhandleData(pose, handleM, isTween)
  }
}

function updatedhandleData (obj, handleM, isTween = false) {
  Object.keys(obj).forEach(key => {
    handleM.setArticulationStage(key.trim(), obj[key] - 0, isTween)
  })
}
async function getCollectData () {
  const res = await getAllCollectData()
  window.sandbox.logger.log('初始化设备...')
  if (res.data && res.data.data.length > 0) {
    window.sandbox.logger.log(res.data)
    CreateAgvGroup(res.data.data)
    res.data.data.forEach(item => {
      const type = getDeviceType(item.modelId)
      switch (type) {
        case 'robot':
          RefreshRobotData(item, false)
          break
        case 'AGV':
          RefreshAGVData(item, false)
          break
        case 'fixture1':
          Refreshfixture1Data(item.modelId, item.collectValue, false)
          break
        case 'fixture2':
          Refreshfixture2Data(item.modelId, item.collectValue, false)
          break
        case 'area13-east13':
        case 'area13-west13':
          RefreshEastArea13Data(item, false)
          break
        case 'plate':
          RefreshPlateData(item, false)
          break
        case 'door':
          RefreshDoorData(item, false)
          break
        case 'Pogo':
          RefreshPogoData(item, false)
          break
        case 'bridge':
          RefreshbridgeData(item, false)
          break
        case 'fixtureInfo':
          RefreshfixtureInfoData(item, false)
          break
      }
    })
  }
}

// 刷新产品
const AGVXJMap = new Map()
function CreateAgvGroup (arryData) {
  const filteredData = arryData.filter(item => item.modelId.includes('AGV'))
  filteredData.forEach(item => {
    AGVXJMap.set(item.modelId, item.collectValue)
  })
  RefreshAGVXJGroup(false)
  // XJDataMapTemp.forEach((value, key) => {
  //   value.visible = false
  // })
}

function StartAgvGroup (arrayData, isTween) {
  for (let i = 0; i < arrayData?.length; i++) {
    const item = arrayData[i]
    if (item?.modelId && AGVXJMap.has(item.modelId)) {
      AGVXJMap.set(item.modelId, item.collectValue)
      RefreshAGVData(item, true)
    }
  }
  if (arrayData.length > 0) {
    const item = arrayData.find(x => x.modelId.includes('AGV'))
    if (item) {
      RefreshAGVXJGroup(isTween)
    }
  }
}

function groupByFixtureNumber (mapdata, threshold = 100) {
  /* ---------- 1. 过滤 + 转 float ---------- */
  const valid = []
  mapdata.forEach((value, key) => {
    const json = JSON.parse(value)
    const liftStr = json.lift
    if (liftStr === '0.00000' || liftStr === null) return
    const liftFloat = parseFloat(liftStr)
    if (liftFloat <= 10) return
    valid.push({ liftFloat, liftStr, agv: key, value: json })
  })
  valid.sort((a, b) => a.liftFloat - b.liftFloat)

  /* ---------- 2. 相邻配对 ---------- */
  const paired = []
  let i = 0
  while (i < valid.length - 1) {
    const curr = valid[i]
    const next = valid[i + 1]
    if (next.liftFloat - curr.liftFloat <= threshold) {
      const deltaX = Math.abs(curr.value.xValue - next.value.xValue)
      paired.push({ curr, next, deltaX })
      i += 2
    } else {
      i += 1
    }
  }

  /* ---------- 3. 型架 ID 自动编号 ---------- */
  const result = []
  let smallIdx = 1; let largeIdx = 3 // P01/P02 小型，P03/P04 大型

  for (const { curr, next, deltaX } of paired) {
    const isSmall = deltaX <= 500
    let id
    if (isSmall) {
      id = `P0${smallIdx++}`
      if (smallIdx > 2) smallIdx = 1 // 循环使用 P01/P02
    } else {
      id = `P0${largeIdx++}`
      if (largeIdx > 4) largeIdx = 3 // 循环使用 P03/P04
    }

    result.push({
      fixturelift: curr.liftStr,
      agvPair: [curr, next],
      deltaX,
      fixtureId: id
    })
  }

  return result
}
function RefreshAGVXJGroup (isTween) {
  const agvGroups = groupByFixtureNumber(AGVXJMap)
  XJDataMapTemp.keys().forEach(key => {
    const item = agvGroups.find(x => x.fixtureId === key)
    if (item) {
      XJDataMapTemp.get(key).visible = true
    } else {
      XJDataMapTemp.get(key).visible = false
    }
  })
  // window.sandbox.logger.log('AGV分组结果:', agvGroups)
  console.log('AGV分组结果:', agvGroups)

  agvGroups.forEach((group, index) => {
    if (group.fixturelift !== '0.00000' || group.fixturelift !== null) {
      const x = (-group.agvPair[0].value.xValue / 1000 + -group.agvPair[1].value.xValue / 1000) / 2
      const z = (group.agvPair[0].value.zValue / 1000 + group.agvPair[1].value.zValue / 1000) / 2
      let yNum = 0
      const y1 = group.agvPair[0].value.lift / 1000
      const y2 = group.agvPair[1].value.lift / 1000
      yNum = y1 > y2 ? y1 : y2
      const value01 = { m0FixtureMOveX: x * 1000, m0FixtureMOveZ: z * 1000, m0FixtureMOveY: yNum * 1000 + 2 * 1000 }
      const item = { modelId: group.fixtureId, collectValue: JSON.stringify(value01) }
      RefreshfixtureTempData(item.modelId, item.collectValue, isTween)
    }
  })
}

let Alldestorymodels = []
// 创建3D标签
async function Create3DLable (ClickcallBack) {
  AreaLableData.forEach(async (item, index) => {
    // testPosion(handellable);
    const boxEffect = await new GCMap.BoxEffect3({
      sandbox: window.sandbox,
      speed: 5,
      position: item.EffectPosition,
      scale: item.EffectScale,
      width: 0.5
    })
    boxEffect.visible = false
    Alldestorymodels.push(boxEffect)
    boxEffect.overlay.userData.ignoreRaycast = true

    // testPosion(boxEffect);
    boxEffect.on('doubleClick', (e) => {
      console.log('点击特效', boxEffect)
    })

    const handellable = await new GCMap.Css3DLable({
      sandbox: window.sandbox,
      position: item.position,
      rotation: item.rotation,
      scale: item.scale,
      text: item.lable,
      id: index,
      image: item.image,
      imageWidth: '250px',
      imageHigh: '71px',
      EnableLookAtCamera: true,
      ClickcallBack,
      target: boxEffect,
      fountOffect: { x: 0, y: 0, z: 0 },
      fontSize: '24px'
    })
    Alldestorymodels.push(handellable)
  })
  addEvent()
}
let css3dElements = []
function addEvent () {
  window.addEventListener('dblclick', onMouseClick)
}
function onMouseClick (event) {
  // 检测 CSS3D 对象（手动计算）
  if (css3dElements.length === 0) {
    css3dElements = document.querySelectorAll('.element')
  }
  css3dElements.forEach(element => {
    const rect = element.getBoundingClientRect()
    if (event.clientX >= rect.left && event.clientX <= rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom) {
      // console.log("点击了 CSS3D 面板:", element);
      element.click() // 触发 DOM 点击事件
    }
  })
}

function testPosion (model) {
  let { x, y, z } = model.position
  let { x: scaleX, y: scaleY, z: scaleZ } = model.scale
  const heading = model.heading
  const pitch = model.pitch
  const roll = model.roll
  const highPrecision = 0.01
  const lowPrecision = 1
  let precesion = lowPrecision

  const highHeightPrecision = 0.1
  const lowHeightPrecision = 1
  let height = lowHeightPrecision
  document.addEventListener('keydown', e => {
    switch (e.key) {
      case 'h':
        precesion = highPrecision
        height = highHeightPrecision
        break
      case 'n':
        precesion = lowPrecision
        height = lowHeightPrecision
        break
      case 'ArrowUp':
        z -= precesion
        break
      case 'ArrowDown':
        z += precesion
        break
      case 'ArrowLeft':
        x -= precesion
        break
      case 'ArrowRight':
        x += precesion
        break
      case '1':
        y += height
        break
      case '4':
        y -= height
        break
      case '2':
        // heading += 1;
        scaleX += height
        break
      case '5':
        // heading -= 1;
        scaleX -= height
        break
      case '3':
        // pitch += 1;
        scaleY += height
        break
      case '6':
        // pitch -= 1;
        scaleY -= height
        break
      case '7':
        // roll += 1;
        scaleZ += height
        break
      case '8':
        // roll -= 1;
        scaleZ -= height
        break
      case 'r':
        window.sandbox.flyTo({
          y: 30,
          z: 23.109106,
          x: 113.319526,
          pitch: 180,
          heading: -180,
          duration: 6
        })

        break
      case 'm':
        // StandMarkerArry[0].moveTo({ x: 113.31471982517, z: 23.05163806975, y: 10 }, 2)
        // downHandle(tableHead, tableData)
        break
    }
    model.position = { x, y, z }
    model.scale = { x: scaleX, y: scaleY, z: scaleZ }
    model.heading = heading
    model.pitch = pitch
    model.roll = roll
    console.log({ x, z, y, scaleX, scaleY, scaleZ, heading, pitch, roll })
  })
}

function destroyAllModels () {
  Alldestorymodels?.forEach(model => {
    if (typeof model?.destroy === 'function') {
      model.destroy() // 确保 destroy 是函数才调用
    }
    if (model?.isObject3D) {
      window.sandbox?.scene?.remove(model)
    }
  })
  Alldestorymodels = []
}
export { destroyAllModels, Create3DLable, InitSocket, getCollectData, updatedhandleData, ArmDataMap, AGVDataMap, XJDataMap, XJDataMap2, XJDataMapTemp, GYTXDataMap, PogoDataMap, socket }
// #endregion
